﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using m_pricelist.Proposal_Services;
using Microsoft.Office.Interop.Word;
using Microsoft.VisualBasic;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;

namespace m_pricelist._BAL_
{
    class bNewProposal 
    { 
        #region Member Variables

        int lRow {get; set;}
        int j { get; set; }
        int l { get; set; }
        int lwtRow { get; set; }
        int lPSRow { get; set; }

        double dDiscount { get; set; }
        double dSubTotal { get; set; }
        double dTotal { get; set; }

        string sShortName { get; set; }
        string sFileName { get; set; }

        string m_sCurrency { get; set; }
        string m_sFinaldest { get; set; }
        string m_sFirstPort { get; set; }

        //Einhverjar global int út VB - Module 1
        int cIsub { get; set; }
        int cItotal { get; set; }
        int cInumber { get; set; } 
        int cIdiscount { get; set; }
        int cIunits { get; set; }
        int cIname { get; set; }

        string specifier { get; set; }
        string prosenta { get; set; }

        protected bool m_bInnova = false;
        protected bool m_bInstallation = false;
        protected bool b_pricelist = false;
        protected bool b_project = false;
        
        ProposalService ps;
        NewProposal_BAL newProposal = new NewProposal_BAL();
        Type_Installation m_tInstalParam = new Type_Installation();

        Word.Document wdDoc = null;
        Word.Document wdDocTerms = null;
        Word.Document wdProposal = null;
        Word.Table tbl = null;

        Word.Range PRange = null;
        Word.Range rTerms = null;


        ////Excel tilvik sem eru notuð til að ná sambandi við Excel. Þetta er new-að þar sem þetta er notað
        //Excel.Application xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
        //Excel.Workbook xlWorkBook = Globals.ThisAddIn.Application.ActiveWorkbook;
        //Excel.Workbooks xlWorkBookObjects = null;
        //Excel.Worksheet xlSheet = null;

        public Word.Application wdApp = null;
        #endregion

        #region Constructor
        //Smiður
        public bNewProposal()
        {
            lRow = 0;
            j = 0;
            l = 1;
            lwtRow = 0;
            lPSRow = 0;

            dDiscount = 0;
            dSubTotal = 0;
            dTotal = 0;

            sShortName = null;
            sFileName = null;

            //Einhverjar global int út VB - Module 1
            cIsub = 9;
            cItotal = 7;
            cInumber = 3; cIdiscount = 8; cIunits = 6; cIname = 4;

            specifier = "###,##0";
            prosenta = "0.0%";

            ps = new ProposalService();
        }
        #endregion
        #region bNewProposal
        public void GetbNewProposal(Proposal proposal, object sPath, object sFileToOpen, ref Excel.Worksheet xlSheet)  
        {
            //Hér er athugað hvort að Marel Pricelist sé ekki örugglega opið
            try
            {
                string Default_Sheet_Name = "Sheet1";
                if (xlSheet.Name.Equals(Default_Sheet_Name))
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    //Marshal.FinalReleaseComObject(xlWorkBookObjects);
                    Marshal.FinalReleaseComObject(xlSheet);

                    Exception ex = null;
                    throw (ex);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("New proposal can not be open since there is no data to work with. Please open Marel Pricelist.xlsm or Project.xlsm and try again");
            }

            try
            {
                object ReadOnly = true;
                object missing = System.Reflection.Missing.Value;

                m_sFinaldest = proposal.txtFinalAdress_TextChanged();

                if (wdApp == null)
                {
                    wdApp = new Word.Application();
                }
                else
                {
                    wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
                }

                object sInfoPath = Interaction.GetSetting(AppName: "Marel_Consulting", Section: "MFS_Pricelist", Key: "Proposal_Info");
                //wdApp.ScreenUpdating = false;

                //Payment terms formið - radiobuttons
                if (wdProposal == null)
                {
                    wdProposal = wdApp.Documents.Open(sInfoPath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                }
                else
                {
                    wdProposal = (Word.Document)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
                }
                
                //wdDocTerms = wdApp.Documents.Open(sInfoPath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                lPSRow = ps.GetLastUsedCell(3, "PriceSummary", ref xlSheet);
                
                if (sFileToOpen == "")
                {
                    if (proposal.optTwoLang.Checked)
                    {
                        wdDoc = wdApp.Documents.Open(sPath);
                    }
                    else if (proposal.optOneLang.Checked)
                    {
                        wdDoc = wdApp.Documents.Open(sPath);
                    }
                }

                else
                {
                    wdDoc = wdApp.Documents.Open(sFileToOpen);
                }

                if (lPSRow > 9)
                {
                    dSubTotal = Convert.ToDouble(proposal.xlWorkBook.Sheets["Output"].Cells(lPSRow, cIsub).Value);
                    dTotal = Convert.ToDouble(proposal.xlWorkBook.Sheets["Output"].Cells(lPSRow, cItotal).Value);
                }

                foreach (Word.ContentControl objCC in wdDoc.ContentControls)
                {
                    switch (objCC.Tag)
                    {
                        case "Company":
                            {
                                objCC.Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Range("_AccName").Value);
                                break;
                            }
                        case "Project":
                            {
                                objCC.Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Range("_OName").Value);
                                break;
                            }
                        case "Company Address":
                            {
                                objCC.Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Range("_BillingAddress").Value);
                                break;
                            }

                        case "FTerms":
                            {
                                if (proposal.optFob.Checked)
                                {
                                    objCC.Range.Text = "FOB " + ((m_sFinaldest == "") ? m_sFirstPort : m_sFinaldest);
                                }
                                else if (proposal.optCFR.Checked)
                                {
                                    objCC.Range.Text = "CFR " + ((m_sFinaldest == "") ? m_sFirstPort : m_sFinaldest);
                                }
                                else if (proposal.optCIF.Checked)
                                {
                                    objCC.Range.Text = "CIF " + ((m_sFinaldest == "") ? m_sFirstPort : m_sFinaldest);
                                }
                                else if (proposal.optFCA.Checked)
                                {
                                    objCC.Range.Text = "FCA " + ((m_sFinaldest == "") ? m_sFirstPort : m_sFinaldest);
                                }
                                else if (proposal.optCPT.Checked)
                                {
                                    objCC.Range.Text = "CPT " + m_sFinaldest;
                                }
                                else if (proposal.optCIP.Checked)
                                {
                                    objCC.Range.Text = "CIP " + m_sFinaldest;
                                }
                                else if (proposal.optDAP.Checked)
                                {
                                    objCC.Range.Text = "DAP " + m_sFinaldest;
                                }
                                else if (proposal.optDAT.Checked)
                                {
                                    objCC.Range.Text = "DAT " + m_sFinaldest;
                                }
                                break;
                            }

                        case "ItemPrice":
                            {
                                if (dTotal > 0)
                                {

                                    foreach (Word.Table oTable in wdDoc.Tables)
                                    {
                                        //Hér er eytt út því sem fyrir var í töflunni
                                        if (((Strings.InStr(1, oTable.Cell(1, 1).Range.Text, "Item number", CompareMethod.Text) != 0) &
                                        (Strings.InStr(1, oTable.Cell(1, 2).Range.Text, "Item Name", CompareMethod.Text) != 0)))
                                        {
                                            j = oTable.Rows.Count;

                                            for (l = j; l >= 1; l--)
                                            {
                                                oTable.Rows[l].Delete();
                                            }
                                        }
                                    }

                                    dDiscount = 1 - (dSubTotal / dTotal);

                                    if (dDiscount > 0)
                                    {
                                        tbl = wdDoc.Tables.Add(objCC.Range, lPSRow - 8, 6);
                                        tbl.Rows.Height = 1;
                                        tbl.Columns[1].Width = 80;
                                        tbl.Columns[2].Width = 230;
                                        tbl.Columns[3].Width = 35;
                                        tbl.Columns[4].Width = 60;
                                        tbl.Columns[5].Width = 55;
                                        tbl.Columns[6].Width = 60;

                                        tbl.Rows[1].Range.Font.Bold = 1;
                                        tbl.Rows[1].Range.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                                        tbl.Cell(1, 1).Range.Text = "Item number";
                                        tbl.Cell(1, 2).Range.Text = "Item Name";
                                        tbl.Cell(1, 3).Range.Text = "Units";
                                        tbl.Cell(1, 4).Range.Text = "Price(" + m_sCurrency + ")";
                                        tbl.Cell(1, 5).Range.Text = "Discount";
                                        tbl.Cell(1, 6).Range.Text = "Contract Price(" + m_sCurrency + ")";
                                        tbl.Cell(1, 5).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                        tbl.Rows[1].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;
                                    }
                                    else
                                    {
                                        tbl = wdDoc.Tables.Add(objCC.Range, lPSRow - 8, 4);
                                        tbl.Rows.Height = 1;
                                        tbl.Columns[1].Width = 90;
                                        tbl.Columns[2].Width = 250;
                                        tbl.Columns[3].Width = 40;
                                        tbl.Columns[4].Width = 70;

                                        tbl.Rows[1].Range.Font.Bold = 1;
                                        tbl.Rows[1].Range.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                                        tbl.Cell(1, 1).Range.Text = "Item number";
                                        tbl.Cell(1, 2).Range.Text = "Item Name";
                                        tbl.Cell(1, 3).Range.Text = "Units";
                                        tbl.Cell(1, 4).Range.Text = "Price(" + m_sCurrency + ")";
                                        tbl.Cell(1, 4).Range.Text = "Contract Price(" + m_sCurrency + ")";
                                        tbl.Cell(1, 4).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                        tbl.Rows[1].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;
                                    }

                                    lwtRow = 2;

                                    for (lRow = 10; lRow <= lPSRow; lRow++)
                                    {
                                        if (!(proposal.xlWorkBook.Sheets["Output"].Rows[lRow].Hidden))
                                        {
                                            if (Strings.InStr(1, Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cInumber).Value), "Total", CompareMethod.Text) != 0)
                                            {
                                                tbl.Cell(lwtRow, 2).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cInumber).Value);
                                                tbl.Cell(lwtRow, 4).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cItotal).Value.ToString(specifier));
                                                tbl.Cell(lwtRow, 4).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

                                                if (dDiscount > 0)
                                                {
                                                    tbl.Cell(lwtRow, 5).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cIdiscount).Value.ToString(prosenta));
                                                    tbl.Cell(lwtRow, 6).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cIsub).Value.ToString(specifier));
                                                    tbl.Cell(lwtRow, 5).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                                    tbl.Cell(lwtRow, 6).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                                                }
                                                tbl.Rows[lwtRow].Range.Borders[Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                                                tbl.Rows[lwtRow].Range.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;
                                                tbl.Rows[lwtRow].Range.Font.Bold = 1;
                                            }
                                            else
                                            {
                                                //hér kemur efsta línan inn í þetta
                                                tbl.Cell(lwtRow, 1).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cInumber).Value);
                                                tbl.Cell(lwtRow, 2).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cIname).Value);
                                                tbl.Cell(lwtRow, 3).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cIunits).Value);
                                                if (String.IsNullOrEmpty(Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cItotal).Value2)))
                                                {
                                                    String str2 = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cItotal).Value2);
                                                    str2 = " ";
                                                    tbl.Cell(lwtRow, 4).Range.Text = str2;
                                                }
                                                else
                                                {
                                                    tbl.Cell(lwtRow, 4).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cItotal).Value.ToString(specifier));
                                                }
                                                tbl.Cell(lwtRow, 4).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

                                                if (dDiscount > 0)
                                                {
                                                    tbl.Cell(lwtRow, 5).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cIdiscount).Text);
                                                    tbl.Cell(lwtRow, 6).Range.Text = Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cIsub).Value.ToString(specifier));
                                                    tbl.Cell(lwtRow, 5).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                                    tbl.Cell(lwtRow, 6).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                                                }
                                                if (((Strings.InStr(1, Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cItotal).Value), "", CompareMethod.Text) == 0) &
                                                    (Strings.InStr(1, Convert.ToString(proposal.xlWorkBook.Sheets["Output"].Cells(lRow, cInumber).Value), "", CompareMethod.Text) != 0)))
                                                {

                                                    tbl.Rows[lwtRow].Delete();
                                                    lwtRow = lwtRow - 1;
                                                }

                                                //if ((Convert.ToString(xlWorkBook.Sheets["Output"].Cells(lRow, cItotal).Value == null)) && (Convert.ToString(xlWorkBook.Sheets["Output"].Cells(lRow, cInumber).Value != null)))
                                                //{
                                                //    tbl.Rows[lwtRow].Delete();
                                                //    lwtRow = lwtRow - 1;
                                                //}
                                            }
                                        }
                                        else
                                        {
                                            tbl.Rows[lwtRow].Delete();
                                            lwtRow = lwtRow - 1;
                                        }

                                        lwtRow = lwtRow + 1;
                                    }
                                }

                                break;
                            }
                        case "App2aName":
                            {
                                if (proposal.lsbAppIn.Items.Count > 0)
                                {
                                    //
                                    sShortName = proposal.lsbShortNameList[0].ToString();
                                    //Á að vera "sicF-100063 Filleting and Trimming of Salmon"
                                    objCC.Range.Text = sShortName;
                                }
                                else
                                {
                                    sShortName = "App2aName";
                                    objCC.Range.Text = sShortName;
                                }

                                break;
                            }

                        case "App2a":
                            {
                                if (proposal.lsbAppIn.Items.Count > 0)
                                {
                                    sFileName = Strings.Replace(sInfoPath.ToString(), "ProposalInfo.docx", "") + proposal.lsbAppNameList[0].ToString();
                                    wdDocTerms = wdApp.Documents.Open(sFileName); //Þetta á að vera Appname   FILLETING AND TRIMMING OF SALMON     

                                    rTerms = wdDocTerms.Bookmarks["App1"].Range;

                                    PRange = wdDoc.Bookmarks["App2a"].Range;
                                    PRange.FormattedText = rTerms.FormattedText;

                                    PRange.ParagraphFormat.SpaceAfter = 0;

                                    PRange.ParagraphFormat.SpaceBefore = 0;
                                    wdDoc.Bookmarks.Add("App2a", PRange);
                                    wdDocTerms.Close(Type.Missing, Type.Missing, Type.Missing);

                                    rTerms = null;
                                }
                                else
                                {
                                    PRange = wdDoc.Bookmarks["App2a"].Range;
                                    PRange.Text = "App2a";
                                    PRange.ParagraphFormat.SpaceAfter = 0;

                                    PRange.ParagraphFormat.SpaceBefore = 0;
                                    wdDoc.Bookmarks.Add("App2a", PRange);
                                }
                                break;
                            }
                        case "App2bName":
                            {
                                if (proposal.lsbAppIn.Items.Count > 1)
                                {
                                    sShortName = proposal.lsbShortNameList[1].ToString();
                                    objCC.Range.Text = sShortName;
                                }
                                else
                                {
                                    sShortName = "App2bName";
                                    objCC.Range.Text = sShortName;
                                }
                                break;
                            }

                        case "App2b":
                            {
                                if (proposal.lsbAppIn.Items.Count > 1)
                                {
                                    sFileName = Strings.Replace(sInfoPath.ToString(), "ProposalInfo.docx", "") + proposal.lsbAppNameList[1].ToString();

                                    wdDocTerms = wdApp.Documents.Open(sFileName);

                                    rTerms = wdDocTerms.Bookmarks["App1"].Range;

                                    PRange = wdDoc.Bookmarks["App2b"].Range;
                                    PRange.FormattedText = rTerms.FormattedText;
                                    PRange.ParagraphFormat.SpaceAfter = 0;

                                    PRange.ParagraphFormat.SpaceBefore = 0;
                                    wdDoc.Bookmarks.Add("App2b", PRange);
                                    wdDocTerms.Close(Type.Missing, Type.Missing, Type.Missing);
                                    rTerms = null;
                                }
                                else
                                {
                                    PRange = wdDoc.Bookmarks["App2b"].Range;
                                    PRange.Text = "App2b";
                                    PRange.ParagraphFormat.SpaceAfter = 0;

                                    PRange.ParagraphFormat.SpaceBefore = 0;
                                    wdDoc.Bookmarks.Add("App2b", PRange);
                                }
                                break;
                            }
                    }
                }

                //Til að bæta við footer í skjalið
                foreach (Word.Section wordSection in wdDoc.Sections)
                {
                    wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Fields.Update();
                }
                wdDocTerms = null;

                wdProposal.Close(Type.Missing, Type.Missing, Type.Missing);
                wdApp.ScreenUpdating = true;
                wdApp.Visible = true;
                wdDoc.Activate();


                //wdDocTerms.Close(Type.Missing, Type.Missing, Type.Missing);

                //Hreinsa upp
                GC.Collect();
                GC.WaitForPendingFinalizers();

                GC.Collect();
                GC.WaitForPendingFinalizers();

                //System.Runtime.InteropServices.Marshal.ReleaseComObject(PRange);

                //System.Runtime.InteropServices.Marshal.ReleaseComObject(wdDocTerms);

                wdDoc = null;

                proposal.cmdClose_Click(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                ps.CleanUp(string.Empty);
                MessageBox.Show(ex.ToString());
            }
        }
        #endregion

        #region Nýtt proposal
        public void bNewStyle(string sDelivery, Proposal proposal)
        {
            try
            {
                proposal.chkNewSeaOnly_CheckedChanged(this, EventArgs.Empty);

                if (sDelivery == "FOB")
                {
                    proposal.optNewFob_Changed_Custom(m_sFirstPort);
                }
                else if (sDelivery == "CFR")
                {
                    proposal.optNewCFR_Changed_Custom(m_sFinaldest, m_sFirstPort);
                }
                else if (sDelivery == "CIF")
                {
                    proposal.optNewCIF_Changed_Custom(m_sFinaldest, m_sFirstPort);
                }
                else if (sDelivery == "FCA")
                {
                    proposal.optNewFCA_Changed_Custom(m_sFinaldest);
                }
                else if (sDelivery == "CPT")
                {
                    proposal.optNewCPT_Changed_Custom(m_sFinaldest);
                }
                else if (sDelivery == "CIP")
                {
                    proposal.optNewCIP_Changed_Custom(m_sFinaldest);
                }
                else if (sDelivery == "DAP")
                {
                    proposal.optNewDAP_Changed_Custom(m_sFinaldest);
                }
                else if (sDelivery == "DAT")
                {
                    proposal.optNewDAT_Changed_Custom(m_sFinaldest);
                }

                if (m_tInstalParam.bIHardware)
                {
                    proposal.chkNewHardware.Checked = true;
                    m_bInstallation = true;
                }
                else
                {
                    proposal.chkNewHardware.Checked = false;
                }
                if (m_tInstalParam.bTHardware)
                {
                    proposal.chkNewTHardware.Checked = true;
                    m_bInstallation = true;
                }
                else
                {
                    proposal.chkNewTHardware.Checked = false;
                }
                if (m_tInstalParam.bISoftware)
                {
                    proposal.chkNewSoftware.Checked = true;
                    m_bInstallation = true;
                }
                else
                {
                    proposal.chkNewSoftware.Checked = false;
                }
                if (m_tInstalParam.bTSoftware)
                {
                    proposal.chkNewTSoftware.Checked = true;
                    m_bInstallation = true;
                }
                else
                {
                    proposal.chkNewTSoftware.Checked = false;
                }

                proposal.optNewOneLang.Checked = true;
            }

            catch (Exception ex)
            {
                ps.CleanUp(string.Empty);
                MessageBox.Show(ex.ToString());
            }
        }
        
        #endregion
    }
}
